//
//  ContentViewController.m
//  History
//
//  Created by jam on 16/9/6.
//  Copyright © 2016年 kane. All rights reserved.
//

#import "ContentViewController.h"
#import "ContentSetViewController.h"
#import "Reachability.h"
#import "NewsListController.h"
#import "ChannelAddViewController.h"
#import "MoreChannelListCell.h"

@interface ContentViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,UIWebViewDelegate,MoreChannelListCellDelegate,UITextViewDelegate>
{
    //Top View
    __weak IBOutlet UIView *topView;
    __weak IBOutlet UIButton *nameBtn;
    __weak IBOutlet UILabel *markNumLbl;
    __weak IBOutlet UIButton *addBtn;
    __weak IBOutlet UIImageView *icon;
    
    //content
    __weak IBOutlet UIScrollView *contentScroll;
    __weak IBOutlet UIWebView *browserView;
    
    __weak IBOutlet UIView *shareView;
    __weak IBOutlet UIButton *praiseBtn;
    __weak IBOutlet UIImageView *praiseIV;
    __weak IBOutlet UILabel *praiseCountLbl;
    __weak IBOutlet UIButton *shareBtn;
    NSInteger praiseNum;
    
    __weak IBOutlet UIView *newsListView;
    __weak IBOutlet UITableView *newsTable;
    NSMutableArray *newsList;
    
    
    __weak IBOutlet UIView *moreChannelView;
    __weak IBOutlet UITableView *channelTable;
    NSMutableArray *channelList;
    NSDictionary *currentChannel;
    
    __weak IBOutlet UIView *commentListView;
    __weak IBOutlet UITableView *commentTable;
    NSMutableArray *commentList;
    NSMutableArray *viewList;
    
    __weak IBOutlet UIButton *supportBtn;
    
    //Tool View
    __weak IBOutlet UILabel *commentNumLbl;
    __weak IBOutlet UIButton *favoriteBtn;
    
    //更多
    __weak IBOutlet UIView *coverView;
    __weak IBOutlet UIButton *coverBtn;
    __weak IBOutlet UIView *bottomView;
    __weak IBOutlet UIButton *doneBtn;
    __weak IBOutlet UILabel *nightLabel;
    __weak IBOutlet UILabel *brightLabel;
    __weak IBOutlet UILabel *fontLabel;
    __weak IBOutlet UISwitch *nightSwitch;
    __weak IBOutlet UISlider *brightSlider;
    __weak IBOutlet UISegmentedControl *fontSegment;
    
    __weak IBOutlet UIView *commentView;
    
    __weak IBOutlet UIView *inputView;
    __weak IBOutlet UIButton *sendBtn;
    __weak IBOutlet UITextView *inputTV;
    
    __weak IBOutlet UIView *toolListView;
    
    
    
    NSDictionary *articleInfo;
    NSString *articleContent;
    
    NSString *collectID;
    NSString *praiseID;
}

@end

@implementation ContentViewController

@synthesize dataInfo;

- (void)viewDidLoad {
    [super viewDidLoad];
    newsList = [NSMutableArray array];
    channelList = [NSMutableArray array];
    commentList = [NSMutableArray array];
    viewList = [NSMutableArray array];

    [addBtn drawCornerRadius:5];;
    [addBtn drawBorderColor:AppColor Width:.5];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [commentView addGestureRecognizer:tap];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNightMode) name:kChangeNightMode object:nil];
    [icon setImageWithURL:[NSURL URLWithString:dataInfo[@"1"]]];
    [self changeNightMode];
    [supportBtn setImage:[UIImage imageNamed:@"support"]forState:UIControlStateSelected];
    [supportBtn setImage:[UIImage imageNamed:@"support2"]forState:UIControlStateNormal];
    [self registerForKeyboardNotification];
    [inputTV drawCornerRadius:5];
    [inputTV drawBorderColor:[UIColor lightGrayColor] Width:0.5];
    
//    [WXApiManager sharedManager].delegate = self;
    
    NSString *ziti = [[NSUserDefaults standardUserDefaults] objectForKey:@"ziti"];
    fontSegment.selectedSegmentIndex = [ziti integerValue] -1;
    
    sendBtn.layer.cornerRadius = 5;
    
    [self findArcticleInfo];
}

- (void)changeNightMode
{
    [nameBtn setTitleColor:KKColor_Black_LightGary forState:UIControlStateNormal];
    topView.backgroundColor = KKColor_Black_White;
    nightLabel.textColor = KKColor_Black_LightGary;
    brightLabel.textColor = KKColor_Black_LightGary;
    fontLabel.textColor = KKColor_Black_LightGary;
    doneBtn.titleLabel.textColor = KKColor_Black_LightGary;
    [doneBtn setTitleColor:KKColor_DarkGray_White forState:UIControlStateNormal];
    bottomView.backgroundColor = KKColor_DarkGray_Black;
    inputTV.backgroundColor = KKColor_Black_White;
    [sendBtn setTitleColor:KKColor_Black_LightGary forState:UIControlStateNormal];
    inputView.backgroundColor = KKColor_BGColor_GrayToDarkgray;
    toolListView.backgroundColor = KKColor_BGColor_GrayToDarkgray;
    commentView.backgroundColor = KKColor_Black_White;
    [self refreshHtml];
}

- (void)registerForKeyboardNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - Data
- (void)findArcticleInfo
{
    NSDictionary *params = @{@"a_id":[dataInfo[@"a_id"] convertToString],
                             @"e_cid":[[UserEntity sharedUser] getUserID],
                             @"collect_cid":[[UserEntity sharedUser] getUserID]};
    [WebService findArticleDetail:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                articleInfo  = result[@"result"][@"article"][@"value"];
                articleContent = [articleInfo[@"a_content"] convertToString];
                commentNumLbl.text = [articleInfo[@"a_commentcount"] convertToString];
                commentNumLbl.hidden = [commentNumLbl.text integerValue] == 0;
                praiseNum = [articleInfo[@"a_praise"] integerValue];
                praiseCountLbl.text = [NSString stringWithFormat:@"%ld人推荐",(long)praiseNum];
                NSArray *praiseAry = articleInfo[@"evaluate"];
                praiseBtn.selected = praiseAry.count > 0;
                supportBtn.selected = praiseBtn.selected;
                if (praiseAry.count > 0) {
                    NSDictionary *dict = praiseAry.firstObject;
                    praiseID = [dict[@"e_id"] convertToString];
                }
                
                NSArray *collectAry = articleInfo[@"collect"];
                favoriteBtn.selected = collectAry.count > 0;
                if (collectAry.count > 0) {
                    NSDictionary *dict = collectAry.firstObject;
                    collectID = [dict[@"collect_id"] convertToString];
                }
                [self findNewsList];
                [self findChannelList];
                [self findCommentList];
                [self refreshHtml];
            }
        }
    }];
}

- (void)refreshHtml
{
    if (articleContent.length > 0) {
        NSString *htmlString = [NSString stringWithFormat:@"%@",articleContent];
        
        NSString *descstr;
        NSString *dateString = [[NSDate dateWithTimeIntervalSince1970:[articleInfo[@"createTime"] longLongValue]] formattedDateDescription];
        NSString *sourceString = [articleInfo[@"source"] convertToString];
        if (NetStatus == ReachableViaWiFi) {
            descstr =  [NSString stringWithFormat:@"<head><style>img{max-height:%dpx !important;}</style><style> body p {background-color:%@!important;}</style></head><body><h2 style='color: #404040;padding: 0 0 .2rem;'>%@</h2><h2 style='margin: 0 0 .12rem;font-size: 10px;color: #888;font-weight: 400;'><span>%@</span><span style='padding-left: .2rem;'>%@</span></h2>%@</body>",0,IS_NightMode?@"#000":@"#fff",[articleInfo[@"a_title"] convertToString],dateString,sourceString,htmlString];
        }else{
            descstr =  [NSString stringWithFormat:@"<head><style>img{max-width:%fpx !important;}</style></head><style> body p {  background-color:%@!important;margin:auto !important; }</style><body><h2 style='color: #404040;padding: 0 0 .2rem;'>%@</h2><h2 style='margin: 0 0 .12rem;font-size: 10px;color: #888;font-weight: 400;'><span>%@</span><span style='padding-left: .2rem;'>%@</span></h2>%@</body>",fWidth_Current - 10,IS_NightMode?@"#000":@"#fff",[articleInfo[@"a_title"] convertToString],dateString,sourceString,htmlString];
        }
        
//        NSString *ziti = [[NSUserDefaults standardUserDefaults] objectForKey:@"ziti"];
//        if ([ziti isEqualToString:@"1"]) {
//            [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '80%'"];
//        }else if ([ziti isEqualToString:@"2"]){
//            [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '90%'"];
//        }else if ([ziti isEqualToString:@"3"]){
//            [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '130%'"];
//        }else if ([ziti isEqualToString:@"4"]){
//            [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '150%'"];
//        }else {
//            [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"];
//        }
        
        [browserView loadHTMLString:descstr baseURL:nil];
        browserView.scrollView.bounces = NO;
        browserView.scrollView.scrollEnabled = NO;
    }
}

- (void)findNewsList
{
    NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"a_channelid":[dataInfo[@"a_channelid"] convertToString],@"a_status":@"",@"pagesize":@"5",@"currentpage":@"1"};
    [WebService findArticleList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                [newsList removeAllObjects];
                NSArray *dataAry = result[@"result"][@"article"][@"value"];
                [newsList addObjectsFromArray:dataAry];
                [newsTable reloadData];
            }
        }
        [self reloadAllFrames];
    }];
}

- (void)findChannelList
{
    NSDictionary *params = @{@"channel_id":articleInfo[@"a_channelid"],@"cs_cid":[[UserEntity sharedUser] getUserID]};
    [WebService findChannelList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *dataAry = result[@"result"][@"channel"][@"value"];
                [channelList removeAllObjects];
                [channelList addObjectsFromArray:dataAry];
                if (channelList.count > 0) {
                    currentChannel = dataAry.firstObject;
                    [nameBtn setTitle:[currentChannel[@"channel_name"] convertToString] forState:UIControlStateNormal];
                    markNumLbl.text = [NSString stringWithFormat:@"%ld人订阅",(long)[currentChannel[@"channel_subscriptioncount"] integerValue]];
                    if ([currentChannel[@"channel_icon"] convertToString].length > 0) {
                        [icon setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",FileURL,currentChannel[@"channel_icon"]]]];
                    }
                    NSArray *ary = currentChannel[@"is_sub"];
                    if (ary.count > 0) {
                        [addBtn setTitle:@"查看" forState:UIControlStateNormal];
                        [addBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                        addBtn.backgroundColor = [UIColor whiteColor];
                    }
                    [channelList removeObjectAtIndex:0];
                }
                [channelTable reloadData];
            }
        }
        [self reloadAllFrames];
    }];
}

- (void)findCommentList
{
    NSDictionary *params = @{@"ac_aid":articleInfo[@"a_id"]};
    [WebService findArticleCommentList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *dataAry = result[@"result"][@"comment"][@"value"];
                [commentList removeAllObjects];
                [viewList removeAllObjects];
                [commentList addObjectsFromArray:dataAry];
                commentNumLbl.text = [NSString stringWithFormat:@"%ld", (long)commentList.count];
                commentNumLbl.hidden = [commentNumLbl.text integerValue] == 0;
                for (int i = 0;i < commentList.count;i++) {
                    [viewList addObject:[self bubbleViewByInfo:commentList[i] index:i]];
                }
                [commentTable reloadData];
            }
        }
        [self reloadAllFrames];
    }];
}

#pragma mark --top view

- (IBAction)backBtnClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)nameBtnClick:(UIButton *)sender
{
    if ([addBtn.titleLabel.text isEqualToString:@"+订阅"] ) {
        ChannelAddViewController *addVC = [[ChannelAddViewController alloc] init];
        addVC.dataInfo = currentChannel;
        [self.navigationController pushViewController:addVC animated:YES];
    }else{
        NewsListController *listVC = [[NewsListController alloc] init];
        listVC.dataInfo = currentChannel;
        [self.navigationController pushViewController:listVC animated:YES];
    }
}

//订阅
- (IBAction)addBtnClick:(UIButton *)sender {
    if (currentChannel == nil) {
        return;
    }
    if ([sender.titleLabel.text isEqualToString:@"+订阅"]) {
        NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"cs_channelid":[currentChannel[@"channel_id"] convertToString]};
        [WebService addMarkChannel:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    [sender setTitle:@"查看" forState:UIControlStateNormal];
                    [sender setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                    sender.backgroundColor = [UIColor whiteColor];
                    NSDictionary *dict = @{@"channel_name":currentChannel[@"channel_name"],@"cs_channelid":currentChannel[@"channel_id"]};
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"addUserchannel" object:dict];
                    [self.view makeToast:@"订阅成功" position:@"center"];
                }
            }
        }];
    }else if ([sender.titleLabel.text isEqualToString:@"查看"]){
        NewsListController *listVC = [[NewsListController alloc] init];
        listVC.dataInfo = currentChannel;
        [self.navigationController pushViewController:listVC animated:YES];
    }
}

#pragma mark - Share View
- (IBAction)sharePraiseClick:(UIButton *)sender {
    if (sender.selected) {
        NSDictionary *params = @{@"e_id":praiseID,@"a_id":articleInfo[@"a_id"]};
        [WebService cancelArticleLike:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    praiseNum --;
                    praiseCountLbl.text = [NSString stringWithFormat:@"%d人推荐",praiseNum];
                    praiseID = @"";
                    praiseBtn.selected = NO;
                    praiseIV.image = [UIImage imageNamed:@"support2"];
                    supportBtn.selected = NO;
                }
            }
        }];
    }else{
        NSDictionary *params = @{@"e_cid":[[UserEntity sharedUser] getUserID],@"e_aid":articleInfo[@"a_id"]};
        [WebService addArticleLike:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    NSDictionary *dict = result[@"result"][@"likeCode"];
                    praiseNum ++;
                    praiseCountLbl.text = [NSString stringWithFormat:@"%d人推荐",praiseNum];
                    praiseID = [dict[@"value"][@"e_id"] convertToString];
                    praiseBtn.selected = YES;
                    supportBtn.selected = YES;
                    praiseIV.image = [UIImage imageNamed:@"support"];
                }else{
                    [self.view makeToast:[result[@"errmsg"] convertToString] position:@"center"];
                }
            }
        }];
    }
}

- (IBAction)shareShareClick:(id)sender {
    
}


#pragma mark - Tool View
//添加评论
-(void)handleTap:(UITapGestureRecognizer *)tap
{
    coverView.hidden = NO;
    [inputTV becomeFirstResponder];
}
//评论数量
- (IBAction)countBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    CGFloat offsetY = 0;
    if (sender.selected) {
        offsetY = moreChannelView.minY;
        if (offsetY + contentScroll.height > contentScroll.contentSize.height) {
            offsetY = contentScroll.contentSize.height - contentScroll.height;
        }
    }
    [contentScroll setContentOffset:CGPointMake(0,offsetY) animated:YES];
}

- (IBAction)starBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        NSDictionary *params = @{@"collect_cid":[[UserEntity sharedUser] getUserID],@"collect_aid":articleInfo[@"a_id"]};
        [WebService addArticleCollect:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    sender.selected = YES;
                    [self.view makeToast:@"收藏成功，将为你推荐更多类似内容" position:@"center"];
                    NSDictionary *dict = result[@"result"][@"collect"][@"value"];
                    collectID = [dict[@"collect_id"] convertToString];
                }
            }
        }];
    } else {//取消收藏
        NSDictionary *params = @{@"collect_id":collectID,@"a_id":articleInfo[@"a_id"]};
        [WebService cancelArticleCollect:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    sender.selected = NO;
                }
            }
            NSLog(@"%@",result[@"errmsg"]);
        }];
    }
    
}

- (IBAction)shareBtnClick:(UIButton *)sender {
    NSMutableArray *items = [NSMutableArray arrayWithObject:@"http://www.baidu.com"];
    UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    [self presentViewController:activity animated:YES completion:nil];
}

- (IBAction)setBtnClick:(UIButton *)sender {
    coverView.hidden = NO;
    [nightSwitch setOn:IS_NightMode ? YES : NO];
    
    [UIView animateWithDuration:0.3 animations:^{
        bottomView.frame = (CGRect){bottomView.minX,358,bottomView.size};
    } completion:^(BOOL finished) {
        
    }];
}

#pragma mark - Tool More

- (IBAction)changeSwitch:(UISwitch *)sender
{
    //夜间模式
    [[NSUserDefaults standardUserDefaults] setObject:@(sender.on) forKey:@"NightMode"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if (sender.on) {
        [[UIScreen mainScreen] setBrightness:0.2];
    }else{
        [[UIScreen mainScreen] setBrightness:0.5];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kChangeNightMode object:nil];
}

- (IBAction)changeSlider:(UISlider *)sender
{
    [[UIScreen mainScreen] setBrightness:sender.value];   
    [[UIScreen mainScreen] setBrightness:sender.value];
}

- (IBAction)changSegment:(UISegmentedControl *)sender
{
    //字体大小
    switch (sender.selectedSegmentIndex) {
        case 0:
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"ziti"];
            [[NSUserDefaults standardUserDefaults] synchronize];
//            [self webViewDidFinishLoad:browserView];
            [self refreshHtml];
            break;
        case 1:
            [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"ziti"];
            [[NSUserDefaults standardUserDefaults] synchronize];
//            [self webViewDidFinishLoad:browserView];
            [self refreshHtml];
            break;
        case 2:
            [[NSUserDefaults standardUserDefaults] setObject:@"3" forKey:@"ziti"];
            [[NSUserDefaults standardUserDefaults] synchronize];
//            [self webViewDidFinishLoad:browserView];
            [self refreshHtml];
            break;
        case 3:
            [[NSUserDefaults standardUserDefaults] setObject:@"4" forKey:@"ziti"];
            [[NSUserDefaults standardUserDefaults] synchronize];
//            [self webViewDidFinishLoad:browserView];
            [self refreshHtml];
            break;
            
        default:
            break;
    }
}

- (IBAction)doneBtnClick:(id)sender {
    coverView.alpha = 1.0;
    [UIView animateWithDuration:0.3 animations:^{
        coverView.alpha = 0.2;
        bottomView.frame = (CGRect){bottomView.minX,568,bottomView.size};
    } completion:^(BOOL finished) {
        coverView.alpha = 1.0;
        coverView.hidden = YES;
    }];
}

#pragma mark - cover view action

- (IBAction)coverBtnPressed:(id)sender {
    [self.view endEditing:YES];
    [self doneBtnClick:nil];
}

- (IBAction)sendBtnPressed:(id)sender {
    if (inputTV.text.length == 0) {
        return;
    }
    NSDictionary *params = @{@"ac_cid":[[UserEntity sharedUser] getUserID],@"ac_aid":[articleInfo[@"a_id"] convertToString],@"ac_content":inputTV.text};
    [WebService addComment:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                [inputTV resignFirstResponder];
                inputTV.text = @"";
                coverView.hidden = YES;
                [self findCommentList];
            }else{
                [self.view makeToast:result[@"errmsg"] position:@"center"];
            }
        }
    }];
}



#pragma mark - UITableView DataSource && Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger dataCount = 0;
    if (tableView == newsTable) {
        dataCount = newsList.count;
    }else if (tableView == channelTable) {
        dataCount = channelList.count;
    }else if (tableView == commentTable) {
        dataCount = commentList.count;
    }
    return dataCount;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    if (tableView == newsTable) {
        height = 40;
    }else if (tableView == channelTable) {
        height = 90;
    }else if (tableView == commentTable) {
        UIView *itemView = [viewList objectAtIndex:[indexPath row]];
        return itemView.frame.size.height;
    }
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == newsTable) {
        static NSString *identifier = @"NewsListCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.textLabel.font = [UIFont fontSize:14.0];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        NSDictionary *item = newsList[indexPath.row];
        cell.textLabel.text = [item[@"a_title"] convertToString];        
        return cell;
    }else if (tableView == channelTable) {
        static NSString *identifier = @"MoreChannelListCell";
        MoreChannelListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            [tableView registerNib:[UINib nibWithNibName:@"MoreChannelListCell" bundle:nil] forCellReuseIdentifier:identifier];
            cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        [cell setupData:channelList[indexPath.row] index:indexPath.row];
        cell.delegate = self;
        return cell;
    }else if (tableView == commentTable) {
        static NSString *identifier = @"CommentListCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        for (UIView *subV in cell.contentView.subviews) {
            [subV removeFromSuperview];
        }
        UIView *itemView = [viewList objectAtIndex:[indexPath row]];
        [cell.contentView addSubview:itemView];
        
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        return cell;
    }
    
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == newsTable) {
        NSDictionary *item = newsList[indexPath.row];
        ContentViewController *detail = [[ContentViewController alloc] init];
        detail.dataInfo = item;
        [self.navigationController pushViewController:detail animated:YES];
    }else if (tableView == channelTable) {
        NSDictionary *item = channelList[indexPath.row];
        NSArray *ary = item[@"is_sub"];
        BOOL isSub = ary.count > 0;
        if (isSub) {
            NewsListController *listVC = [[NewsListController alloc] init];
            listVC.dataInfo = item;
            [self.navigationController pushViewController:listVC animated:YES];
        }else{
            ChannelAddViewController *addVC = [[ChannelAddViewController alloc] init];
            addVC.dataInfo = currentChannel;
            [self.navigationController pushViewController:addVC animated:YES];
        }
    }else if (tableView == commentTable) {
        //        NSDictionary *item = commentList[indexPath.row];
        
    }
}


//组装图文数据
- (UIView *)bubbleViewByInfo:(NSDictionary *)info index:(NSInteger)index
{
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fWidth_Current, 60)];
    returnView.backgroundColor = [UIColor clearColor];
    returnView.userInteractionEnabled = YES;
    CGFloat offsetY = 10;
    CGFloat marginX = 50; //左边距
    CGFloat width = fWidth_Current - 55;
    //头像
    UIButton *avatarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    avatarBtn.frame = CGRectMake(5, offsetY + 10, 40, 40);
    NSString *c_photo = @"";
    if ([info[@"c_photo"] convertToString].length > 0) {
        c_photo = [NSString stringWithFormat:@"%@%@",FileURL,info[@"c_photo"]];
    }
    [avatarBtn setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:c_photo] placeholderImage:[UIImage imageNamed:@"login_user_icon"]];
    [avatarBtn drawCornerRadius:20];
    [avatarBtn addTarget:self action:@selector(avatarClick:) forControlEvents:UIControlEventTouchUpInside];
    [returnView addSubview:avatarBtn];
    //名字
    NSString *author = [info[@"c_nick"] convertToString];
    if (author.length == 0) {
        author = [info[@"ac_id"] convertToString];
    }
    UILabel *nameLbl = [[UILabel alloc] initWithFrame:CGRectMake(marginX, offsetY, width, 20)];
    NSString *htmlString = [NSString stringWithFormat:@"<span style=\"color:#347ada\">%@</span>",author];
    nameLbl.attributedText = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [returnView addSubview:nameLbl];
    
    offsetY = 35;
    //时间
    NSDate *pubtime = [NSDate dateWithTimeIntervalSince1970:[info[@"ac_createtime"] integerValue]];
    UILabel *dateLbl = [[UILabel alloc] initWithFrame:CGRectMake(marginX, offsetY, width, 20)];
    dateLbl.font = [UIFont systemFontOfSize:10];
    dateLbl.textColor = [UIColor grayColor];
    dateLbl.text = [pubtime formattedDateDescription];
    [returnView addSubview:dateLbl];
    [dateLbl sizeToFit];
    
    //content
    if ([info[@"ac_content"] convertToString].length > 0) {
        UILabel *contentLbl = [[UILabel alloc] initWithFrame:CGRectMake(marginX, offsetY, width, 20)];
        contentLbl.font = [UIFont systemFontOfSize:13];
        contentLbl.text = info[@"ac_content"];
        contentLbl.numberOfLines = 0;
        [returnView addSubview:contentLbl];
        [contentLbl sizeToFit];
        offsetY += contentLbl.frame.size.height + 5;
    }
    
    //删除按钮
    if ([[info[@"ac_cid"] convertToString] isEqualToString:[[UserEntity sharedUser] getUserID]]) {
        UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        delBtn.frame = CGRectMake(marginX + dateLbl.frame.size.width, offsetY, 40, 20);
        delBtn.backgroundColor = [UIColor clearColor];
        [delBtn setTitle:@"删除" forState:UIControlStateNormal];
        [delBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        delBtn.titleLabel.font = [UIFont systemFontOfSize:10];
        delBtn.tag = index;
        [delBtn addTarget:self action:@selector(delBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [returnView addSubview:delBtn];
    }
    dateLbl.frame = CGRectMake(marginX, offsetY, width, 20);
    
    
    UILabel *pnumLbl = [[UILabel alloc] initWithFrame:CGRectMake(fWidth_Current - 90 - 25, 20, 20, 20)];
    pnumLbl.font = [UIFont systemFontOfSize:11];
    pnumLbl.textColor = [UIColor grayColor];
    pnumLbl.textAlignment = NSTextAlignmentCenter;
    pnumLbl.text = @"1";
    [returnView addSubview:pnumLbl];
    
    //赞
    UIButton *pbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    pbtn.frame = CGRectMake(fWidth_Current - 70, 20, 20, 20);
    [pbtn setImage:[UIImage imageNamed:@"support"] forState:UIControlStateSelected];
    [pbtn setImage:[UIImage imageNamed:@"support1"] forState:UIControlStateNormal];
    [pbtn addTarget:self action:@selector(praiseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    pbtn.tag = index;
    NSArray *ary = info[@"is_like"];
    pbtn.selected = ary.count > 0;
    [returnView addSubview:pbtn];
    
    //评论
    UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    commentBtn.frame = CGRectMake(fWidth_Current - 35, 20, 20, 20);
    [commentBtn setImage:[UIImage imageNamed:@"comment2"] forState:UIControlStateNormal];
    commentBtn.tag = index;
    [commentBtn addTarget:self action:@selector(commentBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [returnView addSubview:commentBtn];
    UIImageView *commentIV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 10, 10)];
    commentIV.image= [UIImage imageNamed:@"quan_btn_icon02"];
    [commentBtn addSubview:commentIV];
    
    offsetY += 25;
    //灰色背景
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(marginX, offsetY, width, 0)];
    grayView.backgroundColor = KKColor_NavLineColor;
    [returnView addSubview:grayView];
    
    offsetY = 0;
    //赞
    NSArray *praiseAry = info[@"praise"][@"praise"];
    if (praiseAry.count > 0) {
        //点赞icon
        UIImageView *iconIV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 10, 10)];
        iconIV.image= [UIImage imageNamed:@"support1"];
        [grayView addSubview:iconIV];
        //点赞人
        NSMutableArray *nameAry = [NSMutableArray array];
        for (NSDictionary *dict in praiseAry) {
            NSString *temp = @"";
            if (![nameAry containsObject:temp]) {
                [nameAry addObject:temp];
            }
        }
        NSString *praiseHtml = [NSString stringWithFormat:@"<span style=\"color:#347ada\">%@</span>",[nameAry componentsJoinedByString:@"</span>,<span style=\"color:#347ada\">"]];
        UILabel *praiseLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 2, width - 25, 0)];
        praiseLbl.font = [UIFont systemFontOfSize:10];
        praiseLbl.numberOfLines = 0;
        praiseLbl.attributedText = [[NSAttributedString alloc] initWithData:[praiseHtml dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
        [grayView addSubview:praiseLbl];
        [praiseLbl sizeToFit];
        
        offsetY += praiseLbl.frame.size.height + 5;
    }
    
    //评论
    NSArray *replyAry = info[@"reply"][@"riderscircle"];
    if (replyAry.count > 0) {
        for (NSDictionary *dict in replyAry) {
            UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, offsetY, width - 10, 0)];
            lbl.font = [UIFont systemFontOfSize:9];
            lbl.numberOfLines = 0;
            NSString *html = @"";
            NSString *aname = @"";
            if ([dict[@"nickname"] convertToString].length != 0) {
                aname = dict[@"nickname"];
            }else if ([dict[@"truename"] convertToString].length != 0){
                aname = dict[@"truename"];
            }else{
                aname = [dict[@"username"] convertToString];
            }
            
            NSString *bname = @"";
            if ([dict[@"tonickname"] convertToString].length !=0) {
                bname = dict[@"tonickname"];
            }else if ([dict[@"totruename"] convertToString].length != 0){
                bname = dict[@"totruename"];
            }else{
                bname = [dict[@"tousername"] convertToString];
            }
            if ([[dict[@"username"] convertToString] isEqualToString:[dict[@"tousername"] convertToString]]) {
                //作者发的
                html = [NSString stringWithFormat:@"<span style=\"color:#347ada\">%@</span>:%@",aname,[dict[@"content"] convertToString]];
            }else{
                html = [NSString stringWithFormat:@"<span style=\"color:#347ada\">%@</span>回复<span style=\"color:#347ada\">%@</span>:%@",aname,bname,[dict[@"content"] convertToString]];
            }
            
            lbl.attributedText = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
            [grayView addSubview:lbl];
            [lbl sizeToFit];
            offsetY += lbl.frame.size.height + 5;
        }
    }
    
    CGRect frame = grayView.frame;
    frame.size.height = offsetY;
    grayView.frame = frame;
    //底部线
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, grayView.frame.origin.y + grayView.frame.size.height + 5, fWidth_Current, 1)];
    line.backgroundColor = KKColor_NavLineColor;
    [returnView addSubview:line];
    
    frame = returnView.frame;
    frame.size.height = line.frame.origin.y + line.frame.size.height;
    returnView.frame = frame;
    return returnView;
}



- (void)avatarClick:(id)sender
{
    
}

-(void)delBtnClick:(UIButton *)sender
{
    NSDictionary *item = commentList[sender.tag];
    //删除评论方法
    NSDictionary *params = @{@"ac_id":item[@"ac_id"]};
    
    [WebService deletelArticlecomment:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                [self findCommentList];
            }
        }
    }];
}

-(void)praiseBtnClick:(UIButton *)sender
{
    if (sender.selected) {
        NSDictionary *params = @{@"e_id":praiseID,@"a_id":articleInfo[@"a_id"]};
        [WebService cancelArticleLike:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    praiseNum --;
                    praiseCountLbl.text = [NSString stringWithFormat:@"%d人推荐",praiseNum];
                    praiseID = @"";
                    praiseBtn.selected = NO;
                    praiseIV.image = [UIImage imageNamed:@"support2"];
                    supportBtn.selected = NO;
                }
            }
        }];
    }else{
        NSDictionary *params = @{@"e_cid":[[UserEntity sharedUser] getUserID],@"e_aid":articleInfo[@"a_id"]};
        [WebService addArticleLike:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    NSDictionary *dict = result[@"result"][@"evaluate"];
                    praiseNum ++;
                    praiseCountLbl.text = [NSString stringWithFormat:@"%ld人推荐",praiseNum];
                    praiseID = [dict[@"value"][@"e_id"] convertToString];
                    praiseBtn.selected = YES;
                    supportBtn.selected = YES;
                    praiseIV.image = [UIImage imageNamed:@"support"];
                }else{
                    [self.view makeToast:[result[@"errmsg"] convertToString] position:@"center"];
                }
            }
        }];
    }
}

-(void)commentBtnClick:(UIButton *)sender
{
    //评论方法
}


- (void)sendValue:(BOOL)value
{
    if (value) {
        [self.view makeToast:@"                 订阅成功!\n精彩内容将呈现在首页中哦~" position:@"center"];
    } else {
        [self.view makeToast:@"已取消订阅" position:@"center"];
    }
}

#pragma mark -  UIWebView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"url == %@  type == %d",request.URL,navigationType);
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    browserView.opaque = NO; //不设置这个值 页面背景始终是白色
    if (IS_NightMode) {
        //夜间模式
        browserView.backgroundColor = [UIColor blackColor];//[UIColor colorWithRed:0.196 green:0.201 blue:0.212 alpha:1.0];
        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#fff'"];
//        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.background='#000'"];
        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('p')[0].setAttribute('style','background-color:#000 !important;')"];

    }else{
        browserView.backgroundColor  = [UIColor whiteColor];
    }
    
    
    NSString *ziti = [[NSUserDefaults standardUserDefaults] objectForKey:@"ziti"];
    NSLog(@"%@",ziti);
    if ([ziti isEqualToString:@"1"]) {
        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '80%'"];
    }else if ([ziti isEqualToString:@"2"]){
        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '90%'"];
    }else if ([ziti isEqualToString:@"3"]){
        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '130%'"];
    }else if ([ziti isEqualToString:@"4"]){
        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '150%'"];
    }else {
        [browserView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'"];
    }
    
    CGRect frame = browserView.frame;
    frame.size.height = 1;
    browserView.frame = frame;
    CGSize fittingSize = [browserView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    browserView.frame = frame;
    
    [self reloadAllFrames];
    
    
    //js方法遍历图片添加点击事件 返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";
    
    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    
    //注入自定义的js方法后别忘了调用 否则不会生效（不调用也一样生效了，，，不明白）
    NSString *resurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    
    NSLog(@"%@",resurlt);
    
}

- (void)reloadAllFrames
{
//    float sizeHeight = [[browserView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];
    browserView.frame = (CGRect){0,0,browserView.width,browserView.scrollView.contentSize.height};
    shareView.frame = (CGRect){shareView.minX,browserView.maxY,shareView.size};
    newsTable.frame = (CGRect){newsTable.origin,newsTable.width,(CGFloat)(newsList.count*40)};
    newsListView.frame = (CGRect){newsListView.minX,shareView.maxY,newsListView.width,newsTable.maxY};
    channelTable.frame = (CGRect){channelTable.origin,channelTable.width,(CGFloat)(channelList.count*90)};
    moreChannelView.frame = (CGRect){moreChannelView.minX,newsListView.maxY,moreChannelView.width,channelTable.maxY};
    commentTable.frame = (CGRect){commentTable.origin,commentTable.width,commentTable.contentSize.height};
    commentListView.frame = (CGRect){commentListView.minX,moreChannelView.maxY,commentListView.width,commentTable.maxY};
    contentScroll.contentSize = CGSizeMake(contentScroll.width, commentListView.maxY);
}

#pragma mark - UITextFieldDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [inputTV endEditing:YES];
        return NO;
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    CGRect inputFrame = inputView.frame;
    if (inputFrame.size.height != textView.contentSize.height + 10 && textView.contentSize.height < 124) {
        inputView.frame = CGRectMake(inputView.frame.origin.x, inputView.frame.origin.y - (textView.contentSize.height + 10 - inputView.frame.size.height), inputView.frame.size.width, textView.contentSize.height + 10);
    }
}

- (IBAction)shareToCircle:(UIButton *)sender {
//    [WXApiRequestHandler sendText:@"https://www.baidu.com" InScene:WXSceneTimeline];
}

- (void)autoMoveKeyBoard:(float)height
{
    int inputY = coverView.frame.size.height - inputView.frame.size.height/2;
    int y = height == 0 ? inputY :inputY - height;
    inputView.center = CGPointMake(inputView.center.x, y);
}


- (void) keyboardWasShown:(NSNotification *) notif{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    float dist;
    UIInterfaceOrientation orientation=[UIApplication sharedApplication].statusBarOrientation;
    switch (orientation) {
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
            dist=keyboardSize.width;
            break;
        case UIInterfaceOrientationPortraitUpsideDown:
        case UIInterfaceOrientationPortrait:
            dist=keyboardSize.height;
            break;
        default:
            dist=0;
            break;
    }
    [self autoMoveKeyBoard:dist];
}

- (void) keyboardWasHidden:(NSNotification *) notif{
    [self autoMoveKeyBoard:0];
}

@end
